package com.chu.cloud.repository;

import com.chu.cloud.entity.DiscountCoupon;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/5/2 18:52
 * @Description:
 */
@RepositoryRestResource
public interface DiscountCouponRepository extends JpaRepository<DiscountCoupon, Integer> {

    /**
     * 当前时间已过期的优惠券列表
     *
     * @param now
     * @return
     */
    List<DiscountCoupon> findByEndTimeLessThanEqual(Date now);

    /**
     * 可领取的店铺优惠券
     *
     * @param shopId
     * @param status
     * @return
     */
    @RestResource(path = "enableReceive", rel = "enableReceive")
    List<DiscountCoupon> findByShopIdAndStatus(@Param("shopId") Integer shopId, @Param("status") Integer status);

    List<DiscountCoupon> findByShopId(@Param("shopId") Integer shopId);

    /**
     * 使用sql控制高并发下 修改数量 -1 操作
     *
     * @param couponId
     * @return
     */
    @Query(value = "update discount_coupon c set c.NUMBER = c.NUMBER -1 where c.id = ? and c.number > 0", nativeQuery = true)
    @Modifying
    @Transactional(rollbackFor = Exception.class)
    int updateCoupon(Integer couponId);
}
